package Controllers;

import Information.PostInfo;
import Information.UserInfo;
import javafx.application.Application;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;

import java.io.*;
import java.net.URL;
import java.util.ResourceBundle;

import static Application.ReadFileToString.readFile;
//代码盗自立新纪禧，很多命名暂时未改
public class MyPostsController extends Application implements Initializable {
    @FXML
    private AnchorPane drafts_fxml;
    @FXML
    private Label drafts1;//推荐框
    @FXML
    private Label drafts2;
    @FXML
    private Label drafts3;
    @FXML
    private Label drafts4;
    @FXML
    private Label drafts5;
    @FXML
    private Label drafts6;
    @FXML
    private Label drafts7;
    @FXML
    private Label drafts8;
    @FXML
    private Label drafts9;
    @FXML
    private Label drafts10;


    @FXML
    private Button edit1;//编辑按钮
    @FXML
    private Button edit2;
    @FXML
    private Button edit3;
    @FXML
    private Button edit4;
    @FXML
    private Button edit5;
    @FXML
    private Button edit6;
    @FXML
    private Button edit7;
    @FXML
    private Button edit8;
    @FXML
    private Button edit9;
    @FXML
    private Button edit10;



    @FXML
    private Button delete1;//删除按钮
    @FXML
    private Button delete2;
    @FXML
    private Button delete3;
    @FXML
    private Button delete4;
    @FXML
    private Button delete5;
    @FXML
    private Button delete6;
    @FXML
    private Button delete7;
    @FXML
    private Button delete8;
    @FXML
    private Button delete9;
    @FXML
    private Button delete10;

    private UserInfo userInfo = new UserInfo();//用户信息,用来在controller之间传递用户信息

    private PostInfo postInfo1 = new PostInfo();//十个帖子对象
    private PostInfo postInfo2 = new PostInfo();
    private PostInfo postInfo3 = new PostInfo();
    private PostInfo postInfo4 = new PostInfo();
    private PostInfo postInfo5 = new PostInfo();
    private PostInfo postInfo6 = new PostInfo();
    private PostInfo postInfo7 = new PostInfo();
    private PostInfo postInfo8 = new PostInfo();
    private PostInfo postInfo9 = new PostInfo();
    private PostInfo postInfo10 = new PostInfo();
    @Override
    public void initialize(URL location, ResourceBundle resources) {
        //Image userAvatar = new Image(userInfo.getAvatar());
        //userImg.setImage(userAvatar);
        setPostDisplay();
    }
    ////
    public void setPostDisplay() {//设置四个显示框的内容
        readUserInfo();//读取用户信息
        String postObject = "src/UserPosts/postObjects/";
        File f = new File(postObject);
        int size = f.listFiles().length ;   //找出个数
        for (int j = size, i = 0; j > 0; j--)
        {
            postObject =  "src/UserPosts/postObjects/" + j + ".ser";
            try(
                    ObjectInputStream ois = new ObjectInputStream(new FileInputStream(postObject)))
            {
                try {//读取第一个帖子对象
                  PostInfo  postInfo = (PostInfo) ois.readObject();
                  if(postInfo.getAuthorId().equals(userInfo.getId()))
                      i++;
                  else continue;
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

            if(i == 1)
                try(
                        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(postObject)))
                {
                    try {//读取第一个帖子对象
                        postInfo1 = (PostInfo) ois.readObject();
                        drafts1.setText(readFile(postInfo1.getTitlePath()));
                        edit1.setVisible(true);
                        delete1.setVisible(true);
                        //post1.setOpacity(0);
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            if(i == 2)
                try(
                        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(postObject)))
                {
                    try {//读取第一个帖子对象
                        postInfo2 = (PostInfo) ois.readObject();
                        edit2.setVisible(true);
                        delete2.setVisible(true);
                        drafts2.setText(readFile(postInfo2.getTitlePath()));
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

            if(i == 3)
                try(
                        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(postObject)))
                {
                    try {//读取第一个帖子对象
                        edit3.setVisible(true);
                        delete3.setVisible(true);
                        postInfo3 = (PostInfo) ois.readObject();
                        drafts3.setText(readFile(postInfo3.getTitlePath()));
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            if(i == 4)
                try(
                        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(postObject)))
                {
                    try {//读取第一个帖子对象

                        postInfo4 = (PostInfo) ois.readObject();
                        edit4.setVisible(true);;
                        delete4.setVisible(true);
                        drafts4.setText(readFile(postInfo4.getTitlePath()));
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            if(i == 5)
                try(
                        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(postObject)))
                {
                    try {//读取第一个帖子对象
                        postInfo5 = (PostInfo) ois.readObject();
                        drafts5.setText(readFile(postInfo5.getTitlePath()));;
                        edit5.setVisible(true);
                        delete5.setVisible(true);
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            if(i == 6)
                try(
                        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(postObject)))
                {
                    try {//读取第一个帖子对象
                        postInfo6 = (PostInfo) ois.readObject();
                        drafts6.setText(readFile(postInfo6.getTitlePath()));
                        edit6.setVisible(true);
                        delete6.setVisible(true);;
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            if(i == 7)
                try(
                        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(postObject)))
                {
                    try {//读取第一个帖子对象
                        postInfo7 = (PostInfo) ois.readObject();
                        drafts7.setText(readFile(postInfo7.getTitlePath()));
                        edit7.setVisible(true);
                        delete7.setVisible(true);;;
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            if(i == 8)
                try(
                        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(postObject)))
                {
                    try {//读取第一个帖子对象
                        postInfo8 = (PostInfo) ois.readObject();
                        drafts8.setText(readFile(postInfo8.getTitlePath()));
                        edit8.setVisible(true);
                        delete8.setVisible(true);;;;
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            if(i == 9)
                try(
                        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(postObject)))
                {
                    try {//读取第一个帖子对象
                        postInfo9 = (PostInfo) ois.readObject();
                        drafts9.setText(readFile(postInfo9.getTitlePath()));
                        edit9.setVisible(true);
                        delete9.setVisible(true);;;;;
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            if(i == 10)
                try(
                        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(postObject)))
                {
                    try {//读取第一个帖子对象
                        postInfo10 = (PostInfo) ois.readObject();
                        drafts10.setText(readFile(postInfo10.getTitlePath()));
                        edit10.setVisible(true);;;;
                        delete10.setVisible(true);
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }



        }

    }

    public void toPostSite(PostInfo postInfo) throws Exception {
        //打开帖子详情。
        try(
                ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("src/UserPosts/currentDrafts.ser")))
        {   //写入当前帖子对象
            oos.writeObject(postInfo);
        } catch (IOException e) {
            e.printStackTrace();
        }
        PostEditController postSite = new PostEditController();//打开帖子详情页
        //postSite.clearInfoForFile("src/UserPosts/currentDrafts.ser");
        postSite.start(new Stage());
    }
    public void toPost_1_Site() throws Exception {//第一个推荐框
        toPostSite(postInfo1);//调用打开第一个帖子详情页
    }
    public void toPost_2_Site() throws Exception {//第二个推荐框
        toPostSite(postInfo2);//调用打开第二个帖子详情页
    }
    public void toPost_3_Site() throws Exception {//第三个推荐框
        toPostSite(postInfo3);//调用打开第三个帖子详情页
    }
    public void toPost_4_Site() throws Exception {//第四个推荐框
        toPostSite(postInfo4);//调用打开第四个帖子详情页
    }
    public void toPost_5_Site() throws Exception {//第一个推荐框
        toPostSite(postInfo5);//调用打开第一个帖子详情页
    }
    public void toPost_6_Site() throws Exception {//第二个推荐框
        toPostSite(postInfo6);//调用打开第二个帖子详情页
    }
    public void toPost_7_Site() throws Exception {//第三个推荐框
        toPostSite(postInfo7);//调用打开第三个帖子详情页
    }
    public void toPost_8_Site() throws Exception {//第四个推荐框
        toPostSite(postInfo8);//调用打开第四个帖子详情页
    }
    public void toPost_9_Site() throws Exception {//第一个推荐框
        toPostSite(postInfo9);//调用打开第一个帖子详情页
    }
    public void toPost_10_Site() throws Exception {//第二个推荐框
        toPostSite(postInfo10);//调用打开第二个帖子详情页
    }



    public void delete(PostInfo postInfo) throws Exception {
        //首先提取文件名称的数字
        String str = postInfo.getTextPath();
        str=str.trim();
        String str2="";
        if(str != null && !"".equals(str)){  //提取数字
            for(int i=0;i<str.length();i++){
                if(str.charAt(i)>=48 && str.charAt(i)<=57){
                    str2+=str.charAt(i);
                }
            }
        }
        File file;
        file = new File("src/UserPosts/postObjects/"+str2+".ser");
        if (file.exists()) {
            file.delete();
        }
        file = new File("src/UserPosts/postTexts/"+str2+".txt");
        if (file.exists()) {
            file.delete();
        }
        file = new File("src/UserPosts/postTitles/"+str2+".txt");
        if (file.exists()) {
            file.delete();
        }
       /* file = new File("src/UserPosts/currentDrafts.ser");
        if (file.exists()) {
            file.delete();
        }*/
        String postObject = "src/UserPosts/postObjects/";
        File f = new File(postObject);
        int size = f.listFiles().length;   //找出个数
        int i;
        i = Integer.valueOf(str2);
        for(int k = i+1;i <= size ;i++,k++)
        {
            File oldFile = new File("src/UserPosts/postObjects/" + k +".ser");
            File newFile = new File("src/UserPosts/postObjects/" + i +".ser");
            try (
                    ObjectInputStream ois = new ObjectInputStream(new FileInputStream(oldFile))
            ) {
                //得到对象,修改对象里面路径
                PostInfo  draftsInfo = (PostInfo) ois.readObject();
               /* PostInfo  Info  = new PostInfo();
                Info.setPostId(draftsInfo.getPostId());
                Info.setTag(draftsInfo.getTag());
                Info.setCreatedTime(draftsInfo.getCreatedTime());*/
                draftsInfo.setTextPath("src/UserPosts/postTexts/" + i  +".txt");
                draftsInfo.setTitlePath("src/UserPosts/postTitles/" + i +".txt");

                //将新的对象放入
                try(
                        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(oldFile)))
                {   //写入当前帖子对象
                    oos.writeObject(draftsInfo);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } catch (IOException | ClassNotFoundException e) {
                e.printStackTrace();
            }



            oldFile.renameTo(newFile);
            oldFile = new File("src/UserPosts/postTexts/" + k +".txt");
            newFile = new File("src/UserPosts/postTexts/" + i  +".txt");
            oldFile.renameTo(newFile);
            oldFile = new File("src/UserPosts/postTitles/" + k +".txt");
            newFile = new File("src/UserPosts/postTitles/" + i +".txt");
            oldFile.renameTo(newFile);

        }
       MyPostsController news=new MyPostsController();
        news.start(new Stage());
        Stage drafts = (Stage)drafts_fxml.getScene().getWindow();
        drafts.close();

        try{
            Thread.sleep(500);
        }catch(Exception e){
            System.exit(0);//退出程序
        }
        String info="删除成功";
        Alert alert = new Alert(Alert.AlertType.INFORMATION, info, new ButtonType("确定", ButtonBar.ButtonData.YES));
        alert.setHeaderText(null);
        alert.setTitle("提示");
        alert.show();

    }
    public void delete_1() throws Exception {//第一个推荐框
        delete(postInfo1);//调用打开第一个帖子详情页
    }
    public void delete_2() throws Exception {//第二个推荐框
        delete(postInfo2);//调用打开第二个帖子详情页
    }
    public void delete_3() throws Exception {//第三个推荐框
        delete(postInfo3);//调用打开第三个帖子详情页
    }
    public void delete_4() throws Exception {//第四个推荐框
        delete(postInfo4);//调用打开第四个帖子详情页
    }
    public void delete_5() throws Exception {//第一个推荐框
        delete(postInfo5);//调用打开第一个帖子详情页
    }
    public void delete_6() throws Exception {//第二个推荐框
        delete(postInfo6);//调用打开第二个帖子详情页
    }
    public void delete_7() throws Exception {//第三个推荐框
        delete(postInfo7);//调用打开第三个帖子详情页
    }
    public void delete_8() throws Exception {//第四个推荐框
        delete(postInfo8);//调用打开第四个帖子详情页
    }
    public void delete_9() throws Exception {//第一个推荐框
        delete(postInfo9);//调用打开第一个帖子详情页
    }
    public void delete_10() throws Exception {//第二个推荐框
        delete(postInfo10);//调用打开第二个帖子详情页
    }



    @Override
    public void start(Stage primaryStage) throws Exception {
        try {
            AnchorPane root = (AnchorPane) FXMLLoader.load(getClass().getResource("../Resources/MyPosts.fxml"));
            Scene scene = new Scene(root, 765.0, 850.0);
            //scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
            primaryStage.setTitle("我的帖子");
            primaryStage.setScene(scene);
            primaryStage.setResizable(false);
            primaryStage.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }



    public static boolean replaceFileStr(String filepath, String sourceStr, String targetStr) {
        try {
            FileReader fis = new FileReader(filepath); // 创建文件输入流
//			BufferedReader br = new BufferedReader(fis);
            char[] data = new char[1024]; // 创建缓冲字符数组
            int rn = 0;
            StringBuilder sb = new StringBuilder(); // 创建字符串构建器
            // fis.read(data)：将字符读入数组。在某个输入可用、发生 I/O
            // 错误或者已到达流的末尾前，此方法一直阻塞。读取的字符数，如果已到达流的末尾，则返回 -1
            while ((rn = fis.read(data)) > 0) { // 读取文件内容到字符串构建器
                String str = String.valueOf(data, 0, rn);// 把数组转换成字符串
//				System.out.println(str);
                sb.append(str);
            }
            fis.close();// 关闭输入流
            // 从构建器中生成字符串，并替换搜索文本
            String str = sb.toString().replace(sourceStr, targetStr);
            FileWriter fout = new FileWriter(filepath);// 创建文件输出流
            fout.write(str.toCharArray());// 把替换完成的字符串写入文件内
            fout.close();// 关闭输出流
            ;

            return true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }

    }


    public void readUserInfo(){   //读取用户对象信息
        try(
                ObjectInputStream ois = new ObjectInputStream(new FileInputStream("src/UserPosts/currentUser.ser"))) {
            try {//读取当前用户对象
                try {
                    userInfo = (UserInfo) ois.readObject();;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
